package main

import (
	"flag"
	"fmt"
	"os"
	"strings"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

//定义文件上传的核心变量
var (
	endpint    = ""   //oss的外网地域节点地址
	acessKey   = ""   //此账号为限制权限账号，只可访问指定bucket的指定目录
	secretKey  = ""   //此账号为限制权限账号，只可访问指定bucket的指定目录
	bucketName = ""   //测试用的bucket
	uploadFile string //需要上传的文件
	targetFile string //上传后的文件名
)

//定义一个帮助信息的变量
var (
	help bool
)

//上传主程序
func upload(targetFile, uploadFile string) error {
	//创建一个oss的对象并获取到客户端
	client, err := oss.New(endpint, acessKey, secretKey)
	if err != nil {
		return err
	}
	//传入bucket的名字
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		return err
	}
	//开始从文件中推送对象
	err = bucket.PutObjectFromFile("log_parking/mxg/"+targetFile, uploadFile)
	if err != nil {
		return err
	}
	//打印下载url
	downUrl, err := bucket.SignURL("log_parking/mxg/"+targetFile, oss.HTTPGet, 60*60*24)
	if err != nil {
		return fmt.Errorf("sign file download url error,%s", err)
	}
	fmt.Printf("下载链接: %s\n", downUrl)
	fmt.Println("\n注意: 文件下载有效期为1天, 中转站保存时间为3天, 请及时下载")
	return nil
}

//校验核心参数函数
func validate() error {
	if endpint == "" {
		return fmt.Errorf("endpoint missed")
	}

	if acessKey == "" || secretKey == "" {
		return fmt.Errorf("access key or secert key missed")
	}

	if bucketName == "" {
		return fmt.Errorf("bucket name missed")
	}
	return nil
}

//编写帮助信息
func usage() {
	fmt.Fprintf(os.Stderr, `cloud-station version: 0.0.1
Usage: cloud-station [-h] -f <uplaod file path>
Options:
`)
	flag.PrintDefaults()
}

//main程序
func main() {
	//解析flag参数
	flag.Parse()
	//判断是否是帮助的需求
	if help {
		flag.Usage()
		os.Exit(0)
	}
	//启动校验参数
	if err := validate(); err != nil {
		fmt.Printf("validate paras error\n%s\n", err)
		os.Exit(-1)
	}
	//判断上传文件名是否带路径
	if strings.Contains(uploadFile, "/") {
		uploadFiles := strings.Split(uploadFile, "/")
		targetFile = uploadFiles[len(uploadFiles)-1]
	} else {
		targetFile = uploadFile
	}
	//启动上传程序
	if err := upload(targetFile, uploadFile); err != nil {
		fmt.Printf("upload file error,%s", err)
		os.Exit(-1)
	}
	fmt.Printf("upload file %s success!", uploadFile)
}

//初始化函数
func init() {
	flag.BoolVar(&help, "h", false, "这是一个帮助")
	flag.StringVar(&uploadFile, "f", "go.sum", "指定上传文件名字")
	flag.Usage = usage

}
